const ossUnloadFiles = require('./ossutil/uploadFile.js')
const api = require('./api.js')
import uploadImage from '@/pages/utils/ossutil/uploadFile.js'


const uploads = async function(ossPath,path,name,fileSuffix) {
	let _this = this
	
	
	let fileUrl = await getPath(ossPath,path,name)
	let fileType = await attachFileType(path)
	let data = {
		classifyId: fileType.id,
		fileMd5:"0",
		name:name,
		fileTypeDict: fileType.value,
		fileSuffix:fileSuffix,
		fileUrl:fileUrl
	}
	// console.log('获取文件id的请求参数',data)

	const res = await api.myRequest({
		url: '/comm/attachFile',
		method: 'POST',
		data: data
	})
	// console.log('获取文件id',res)
	return res
	
}

const filesMd5 = function(path){
	let reader = new FileReader()
	reader.readAsBinaryString(path)//读取文件
	reader.onload = function(e) {
	    var md5 = Sparkmd5.hashBinary(e.target.result)//获得文件MD5
		return md5
	}
}

/**
 * 获取附件类型接口
 * @param {*} path 文件路径
 */
const attachFileType = async function(path) {
	let _this = this
	let suffix = path.split('.')[1]

	let ids = ''

	const res = await api.myRequest({
		url: '/comm/attachFile/fileType/' + suffix,
	})
	// console.log(res)
	if (res.data.code == 200) {
		return res.data.data
	} else {
		return null
	}
}
/**
 * 兑换oss秘钥
 */
const requsetOss = async function() {
	let _this = this
	const res = await api.myRequest({
		url: "/comm/oss/sts"
	})
	// console.log('获取oss上传临时密钥', res)
	if (res.data.code == 200) {
		getApp().globalData.upLoadAccess = res.data.data
		var time = Date.now()
		getApp().globalData.upLoadAccess.time = time
		return getApp().globalData.upLoadAccess
	} else {
		return ''
	}
}
/**
 * 获取文件上传路径
 */
const getPath = async function(ossPath,path,name) {
	let _this = this
	
	let upLoadAccess = getApp().globalData.upLoadAccess
	if(upLoadAccess==null){
		upLoadAccess = await requsetOss(path)
	}else{
		let nowTime = Date.now()
		let time = upLoadAccess.time
		if ((nowTime - time) > (1000 * 60 * 20)) {
			//当前时间比上次调用时间超过20分钟 重新调用
			upLoadAccess = await requsetOss(path)
		} else {
			
		}
	}
	
	let data = {
		ossPath: ossPath,
		fileName: name
	}
	const res = await api.myRequest({
		url: "/comm/oss/path",
		data: data
	})
	// console.log("storeAs",res)
	let storeAs = res.data.data
	// console.log("storeAs",storeAs)
	let parmas = {
		accessKeyId: upLoadAccess.accessKeyId,
		accessKeySecret: upLoadAccess.accessKeySecret,
		stsToken: upLoadAccess.securityToken
	}
		
	// const ossUplpad = await uploadImage(path,storeAs,parmas)

	await uploadImage(path, storeAs, parmas, result => {
		// console.log('ossUplpadresult',result)
		
	}, err => {
		// console.log(err)
		
	})
	console.log('storeAs',storeAs)
	return storeAs


}


module.exports.uploads = uploads
module.exports.attachFileType = attachFileType
module.exports.requsetOss = requsetOss
module.exports.getPath = getPath

